package cn.edu.lingnan.servlet.course;

import cn.edu.lingnan.pojo.CourseDTO;
import cn.edu.lingnan.service.CourseService;
import cn.edu.lingnan.service.CourseServiceImp;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet({"/pagequery", "/querybyname"})
public class CourseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private CourseService courseService = new CourseServiceImp();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getServletPath();
        try {
            switch (action) {
                case "/pagequery":
                    listCourses(request, response);
                    break;
                case "/querybyname":
                    searchCourses(request, response);
                    break;
                default:
                    listCourses(request, response);
                    break;
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    private void listCourses(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = Integer.parseInt(request.getParameter("page") != null ? request.getParameter("page") : "1");
        int pageSize = Integer.parseInt(request.getParameter("pageSize") != null ? request.getParameter("pageSize") : "10");

        List<CourseDTO> courses = courseService.pageQuery(page, pageSize);
        Integer totalCourses = courseService.getTotalCourses();
        int totalPages = (int) Math.ceil((double) totalCourses / pageSize);

        request.setAttribute("courses", courses);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("currentPage", page);

        request.getRequestDispatcher("/course.jsp").forward(request, response);
    }

    private void searchCourses(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String courseName = request.getParameter("courseName");
        List<CourseDTO> courses = courseService.getCoursesByName(courseName);
          for (CourseDTO course : courses) {
              System.out.println(course);
          }
        request.setAttribute("courses", courses);
        request.setAttribute("currentPage",1);
        request.setAttribute("pageSize", courses.size());
        request.setAttribute("totalPages", 1);
        request.getRequestDispatcher("course.jsp").forward(request, response);
    }
}
